package com.xxx.dit.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xxx.base.utils.R;
import com.xxx.dit.domain.DictItem;
import com.xxx.dit.query.DictItemQuery;
import com.xxx.dit.service.IDictItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dictItem")
@Api(tags = "数据字典详情接口类")
public class DictItemController {

    @Autowired
    private IDictItemService dictItemService;

    @GetMapping
    @ApiOperation(value = "查询所有数据字典详情")
    public List<DictItem> findAll() {
        return dictItemService.findAll();
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询数据字典详情")
    public R<DictItem> findOne(@PathVariable long id) {
        DictItem dictItem = dictItemService.findOne(id);
        return R.ok(dictItem);
    }

    @PostMapping
    @ApiOperation(value = "分页加条件查询")
    public R<PageInfo<DictItem>> queryPage(@RequestBody DictItemQuery dictItemQuery) {
        List<DictItem> list = dictItemService.queryPage(dictItemQuery);
        PageHelper.startPage(dictItemQuery.getCurrentPage(), dictItemQuery.getPageSize());
        return R.ok(new PageInfo<DictItem>(list));
    }

    @PutMapping
    @ApiOperation(value = "增加或者修改数据字典详情")
    public R<Void> updateAndAddDictItem(@RequestBody DictItem dictItem) {
        try {
            Long id = dictItem.getId();

            if (id == null) {
                dictItemService.addDictItem(dictItem);
            } else {
                dictItemService.updateDictItem(dictItem);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("数据字典名称已存在");
        }
        return R.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "通过ID删除数据字典详情")
    public R<Void> deleteDictItem(@PathVariable long id) {
        try {
            dictItemService.deleteDictItem(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    @PatchMapping
    @ApiOperation(value = "批量删除数据字典详情")
    public R<Void> batchDictItems(@RequestBody long[] ids) {
        try {
            dictItemService.batchDictItems(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    //获取明细
    @GetMapping("/findByDictId/{dictId}")
    @ApiOperation(value = "通过ID查询数据字典")
    public R<List<DictItem>> findOne(@PathVariable Long dictId) {
        PageHelper.clearPage();
        return R.ok(dictItemService.findByDictId(dictId));
    }

}
